﻿using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Spi;
using SBlogCore.Common.DatabaseAccessor.Repositorys.EFCore;
using SBlogCore.Entitys.SystemManager;
using SBlogCore.TaskJob.Models;
using Microsoft.EntityFrameworkCore;

namespace SBlogCore.TaskJob.HostServices
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class QuartzService : IHostedService, IDisposable
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IRepository<SysOpenJob> _openJobRepository;

        public QuartzService(ISchedulerFactory schedulerFactory, IRepository<SysOpenJob> openJobRepository)
        {
            _schedulerFactory = schedulerFactory ?? throw new ArgumentNullException(nameof(schedulerFactory));
            _openJobRepository = openJobRepository;
        }
        public IScheduler? Scheduler { get; set; }
        /// <summary>
        /// 开启
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
            var runStatus = (int) JobStatus.Running;
            List<SysOpenJob> jobSchedules = await _openJobRepository.Where(w => w.Status== runStatus).ToListAsync(cancellationToken: cancellationToken);
            OpenJobBuilder jobExtend =  OpenJobBuilder.Build(Scheduler);
            foreach (var jobSchedule in jobSchedules)
            {
                await jobExtend.BindJob(jobSchedule).RunAsync(cancellationToken);
                jobSchedule.Status = (int)JobStatus.Scheduling;
            }
            await Scheduler.Start(cancellationToken);
            await Console.Out.WriteLineAsync("定时任务开启！");
        }
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Scheduler?.Shutdown(cancellationToken)!;
            await Console.Out.WriteLineAsync("定时任务关闭！");
        }

        public void Dispose()
        {
            
        }
    }
}
